package com.kch.web.controller.system;

import com.kch.common.annotation.Log;
import com.kch.common.core.controller.BaseController;
import com.kch.common.core.domain.AjaxResult;
import com.kch.common.core.page.TableDataInfo;
import com.kch.common.enums.BusinessType;
import com.kch.common.utils.DateUtils;
import com.kch.common.utils.bean.BeanUtils;
import com.kch.framework.util.ShiroUtils;
import com.kch.system.domain.AuditRecord;
import com.kch.system.domain.Enterprise;
import com.kch.system.service.AuditRecordService;
import com.kch.system.service.EnterpriseService;
import com.kch.system.vo.AuditRecordVO;
import com.kch.system.vo.EnterpriseVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/system/enterprise")
@Api(tags = "企业")
public class EnterpriseController extends BaseController {

    private String prefix = "system/enterprise";

    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private AuditRecordService auditRecordService;

    @GetMapping()
    public String index(ModelMap mmap) throws Exception {
        mmap.put("ent", enterpriseService.selectByUserId(ShiroUtils.getUserId().intValue()));
        return prefix + "/add";
    }


    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(@Valid EnterpriseVO enterpriseVO) {
        Enterprise enterprise;
        if (ObjectUtils.isEmpty(enterpriseVO.getId())) {
            enterprise = new Enterprise();
            BeanUtils.copyProperties(enterpriseVO, enterprise);
            enterprise.setCreateBy(ShiroUtils.getLoginName());
            enterprise.setLogoImg(enterpriseVO.getImageurl());
            enterprise.setUserId(ShiroUtils.getUserId().intValue());
            enterpriseService.insertEnterprise(enterprise);

            AuditRecord auditRecord = new AuditRecord();
            auditRecord.setBusId(enterprise.getId());
            auditRecord.setBusType("1");
            auditRecord.setReviewStatus("0");
            auditRecord.setOperTime(new Date());
            auditRecord.setOperUser(ShiroUtils.getUserId().intValue());
            auditRecord.setOpinion("待审核");
            auditRecord.setCreateBy(ShiroUtils.getLoginName());
            auditRecord.setCreateTime(new Date());
            auditRecordService.insertAuditRecord(auditRecord);
        } else {
            Enterprise userEnt = enterpriseService.selectByUser(ShiroUtils.getUserId().intValue());
            if("2".equals(userEnt.getStatus())){
                userEnt.setStatus("0");
            }
            userEnt.setCode(enterpriseVO.getCode());
            userEnt.setLogoImg(enterpriseVO.getImageurl());
            userEnt.setLicenseImg(enterpriseVO.getLicenseImg());
            userEnt.setName(enterpriseVO.getName());
            userEnt.setLinkName(enterpriseVO.getLinkName());
            userEnt.setLinkPhone(userEnt.getLinkPhone());
            userEnt.setRemark(userEnt.getRemark());
            userEnt.setUpdateBy(ShiroUtils.getLoginName());
            enterpriseService.updateById(userEnt);
        }
        return AjaxResult.success("注册成功");
    }

    @GetMapping("/getDetail")
    @ResponseBody
    @ApiOperation("查询企业详情, 审核状态, 0: 待审核 1:审核通过 2.审核不通过")
    public AjaxResult getEnterprise() {
        EnterpriseVO enterpriseVO = enterpriseService.selectByUserId(ShiroUtils.getUserId().intValue());
        return AjaxResult.success(enterpriseVO);
    }

    @PostMapping("/addEnterprise")
    @ResponseBody
    @ApiOperation("企业注册")
    public AjaxResult regEnterprise(@RequestBody @Valid EnterpriseVO enterpriseVO) {
        Enterprise enterprise;
        Enterprise exist = enterpriseService.selectPassByUserId(ShiroUtils.getUserId().intValue());
        if(!ObjectUtils.isEmpty(exist)){
            return error("注册企业已通过审核，请勿重复提交！");
        }
        Enterprise userEnt = enterpriseService.selectByUser(ShiroUtils.getUserId().intValue());
        if (ObjectUtils.isEmpty(userEnt)) {
            enterprise = new Enterprise();
            BeanUtils.copyProperties(enterpriseVO, enterprise);
            enterprise.setCreateBy(ShiroUtils.getLoginName());
            enterprise.setLogoImg(enterpriseVO.getImageurl());
            enterprise.setUserId(ShiroUtils.getUserId().intValue());
            enterpriseService.insertEnterprise(enterprise);

            AuditRecord auditRecord = new AuditRecord();
            auditRecord.setBusId(enterprise.getId());
            auditRecord.setBusType("1");
            auditRecord.setReviewStatus("0");
            auditRecord.setOperTime(new Date());
            auditRecord.setOperUser(ShiroUtils.getUserId().intValue());
            auditRecord.setOpinion("待审核");
            auditRecord.setCreateBy(ShiroUtils.getLoginName());
            auditRecord.setCreateTime(new Date());
            auditRecordService.insertAuditRecord(auditRecord);
        } else {
            if("2".equals(userEnt.getStatus())){
                userEnt.setStatus("0");
            }
            userEnt.setCode(enterpriseVO.getCode());
            userEnt.setLogoImg(enterpriseVO.getImageurl());
            userEnt.setLicenseImg(enterpriseVO.getLicenseImg());
            userEnt.setName(enterpriseVO.getName());
            userEnt.setLinkName(enterpriseVO.getLinkName());
            userEnt.setLinkPhone(userEnt.getLinkPhone());
            userEnt.setRemark(userEnt.getRemark());
            userEnt.setUpdateBy(ShiroUtils.getLoginName());
            enterpriseService.updateById(userEnt);
        }
        return AjaxResult.success("注册成功");
    }



    @GetMapping("/index")
    public String indexPage(ModelMap mmap) throws Exception {
        return prefix + "/enterprise";
    }


    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Enterprise enterprise) {
        startPage();
        List<Enterprise> list = enterpriseService.selectEnterprisePage(enterprise);
        return getDataTable(list);
    }

    @GetMapping("/detail/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        mmap.put("ent", enterpriseService.selectVOById(id));
        return prefix + "/detail";
    }


    @GetMapping("/audit/{id}")
    public String audit(@PathVariable("id") Integer id, ModelMap mmap) throws Exception {
        mmap.put("id", id);
        return prefix + "/audit";
    }

    @PostMapping("/audit")
    @ResponseBody
    public TableDataInfo auditList(@RequestParam("id") Integer id) throws Exception {
        if(ObjectUtils.isEmpty(id)){
            List<AuditRecordVO> auditRecords = new ArrayList<>();
            return getDataTable(auditRecords);
        }
        startPage();
        List<AuditRecordVO> auditRecords = auditRecordService.selectByBusId(id, "1");
        return getDataTable(auditRecords);
    }

    @GetMapping("/pass/{id}")
    public String pass(@PathVariable("id") Integer id, ModelMap mmap) throws Exception {
        mmap.put("id", id);
        mmap.put("userName", ShiroUtils.getLoginName());
        mmap.put("date", DateUtils.parseDateToStr("yyyy-MM-dd", new Date()));
        mmap.put("status", "审核通过");
        return prefix + "/pass";
    }

    @Log(title = "审核通过", businessType = BusinessType.INSERT)
    @PostMapping("/pass")
    @ResponseBody
    public AjaxResult pass(AuditRecordVO auditRecordVO){
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setBusId(auditRecordVO.getId());
        auditRecord.setBusType("1");
        auditRecord.setReviewStatus("1");
        auditRecord.setOperTime(new Date());
        auditRecord.setOperUser(ShiroUtils.getUserId().intValue());
        auditRecord.setOpinion(auditRecordVO.getOpinion());
        auditRecord.setCreateBy(ShiroUtils.getLoginName());
        auditRecord.setCreateTime(new Date());
        auditRecordService.insertAuditRecord(auditRecord);

        Enterprise enterprise = enterpriseService.selectById(auditRecordVO.getId());
        enterprise.setStatus("1");
        enterpriseService.updateById(enterprise);
        return AjaxResult.success();
    }

    @GetMapping("/fail/{id}")
    public String fail(@PathVariable("id") Integer id, ModelMap mmap) throws Exception {
        mmap.put("id", id);
        mmap.put("userName", ShiroUtils.getLoginName());
        mmap.put("date", DateUtils.parseDateToStr("yyyy-MM-dd", new Date()));
        mmap.put("status", "审核不通过");
        return prefix + "/fail";
    }

    @Log(title = "审核不通过", businessType = BusinessType.INSERT)
    @PostMapping("/fail")
    @ResponseBody
    public AjaxResult fail(AuditRecordVO auditRecordVO){
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setBusId(auditRecordVO.getId());
        auditRecord.setBusType("1");
        auditRecord.setReviewStatus("2");
        auditRecord.setOperTime(new Date());
        auditRecord.setOperUser(ShiroUtils.getUserId().intValue());
        auditRecord.setOpinion(auditRecordVO.getOpinion());
        auditRecord.setCreateBy(ShiroUtils.getLoginName());
        auditRecord.setCreateTime(new Date());
        auditRecordService.insertAuditRecord(auditRecord);

        Enterprise enterprise = enterpriseService.selectById(auditRecordVO.getId());
        enterprise.setStatus("2");
        enterpriseService.updateById(enterprise);
        return AjaxResult.success();
    }


    @GetMapping("/checkEnterpriseIsPass")
    @ResponseBody
    @ApiOperation("校验当前用户绑定企业是否审核通过 true:通过 ; false: 未通过")
    public AjaxResult checkEnterpriseIsPass(){
        boolean result = enterpriseService.enterPriseIsPass(ShiroUtils.getUserId().intValue());
        return AjaxResult.success(!result);
    }
}
